Formius.Element_Container_Repeat = $.inherit(Formius.Element_Container, {
	repeat: {
		min: 1,
		max: 10
	},
	template: null,

	__constructor: function(element, form, settings) {
		this.__base(element, form, settings);
		for (var i = 0, len = this._elements.length; i < len; i++) {
			if ('isTemplate' in this._elements[i] && this._elements[i].isTemplate()) {
				this.setTemplate(this._prepareTemplate(this._elements[i].getElement().clone()));
				this.remove(this._elements[i]);
				break;
			}
		}
		if (!this.template && this._elements.length) {
			this.setTemplate(this._prepareTemplate(this._elements[0].getElement().clone()));
		}
	},

	_prepareTemplate: function(template) {
		return template
			.removeClass(this.settings.classes.repeat.template + ' f-id' + $.identify(template))
			.addClass(this.settings.classes.repeat.row);
	},

	_parseOptions: function(options) {
		if (!options) {
			return this;
		}
		this.__base(options);
		this.repeat = Formius.Helper.extend(this.repeat, options.repeat);
		return this;
	},


	add: function(element, index) {
//		console.log('aaa: ' + index);
		this.addElement(this.createElement(element), index);
		return this;
	},
	canAdd: function() {
		return (this.count() < (this.repeat.max || 10));
	},
	canRemove: function() {
		return (this.count() > (this.repeat.min || 1));
	},
	count: function() {
		var count = 0, elements = this.getElements();
		for (var i = 0, len = elements.length; i < len; i++) {
			if (elements[i] && 'isTemplate' in elements[i] && !elements[i].isTemplate()) {
				count++;
			}
		}
		return count;
	},
	down: function(element) {
		if (element && 'getElement' in element) {
			this.trigger(this.__self.EVENT_DOWN, element);
		}
		return this;
	},
	getTemplate: function() {
		return this.template;
	},
	setTemplate: function(template) {
		if (template && Formius.Helper.isObject(template) && 'clone' in template) {
			this.template = template;
		}
	},
	up: function(element) {
		if (element && 'getElement' in element) {
			this.trigger(this.__self.EVENT_UP, element);
		}
		return this;
	}
}, {
	EVENT_UP: 'up',
	EVENT_DOWN: 'down'
});

